<template>
	<view>
		<view class="">
			<!-- 添加商品 -->
			<view
				style="display: flex;width: 700rpx;background-color: white;border-radius: 20rpx;margin: 20rpx auto 0 auto;align-items: center;height: 100rpx;"
				@click="to_goods()">
				<uni-icons style="margin-left: 35rpx;margin-right: 20rpx;" type="plusempty" size="20"></uni-icons>
				添加商品！
			</view>
			<view v-if="is_nogoods==0">
				没有商品
			</view>
			<view v-for="(item,index) in goods_list" :key="index"
				style="display: flex;align-items: center; overflow: hidden; width:700rpx;height: 100rpx; margin: 10rpx auto 15rpx auto;border-radius:15rpx;box-shadow: 2rpx 2rpx 3rpx 4rpx #c2c2c2;padding: 10rpx 0;"
				@click="to_goods(item)">
				<!-- <image style="width: 100rpx;height: 100rpx;border-radius: 10rpx;margin-left: 15rpx;"
					:src="item.tupian_url[0].fileID" mode=" scaleToFill"></image> -->
				<view
					style="display: flex;margin: 0 10rpx 0 15rpx;flex-direction:row;width: 550rpx;justify-content:space-between;">
					<view style="display: flex;flex-direction:column;">
						{{item.goods_name}}
					</view>
				</view>
				<view style="display: flex;justify-content: end; width: 110rpx;color: red;margin-right: 15rpx;">
					{{item.goods_price}}
				</view>
			</view>
		</view>
		<!-- 下面是点 添加商品使用 -->
		<model v-if='goods_add_show' @colseModel='goods_add_show = false'>
			<scroll-view scroll-y="true" style="display: flex; " :style="{ height: phoneHeight + 'rpx' }">
				<view class="">
					<view style="display: flex;flex-direction: column;">
						<view style="display: flex;margin:0 0 20rpx 0;align-items: center;">
							<view
								style="width:8rpx;height: 30rpx;background-color: blue;margin-right: 15rpx;border-radius: 15rpx;">
							</view>
							选择图片
							<text style="font-size: 23rpx;color: darkgray;margin-left: 10rpx;">(更改时，先删除再重新上传)</text>
						</view>
						<view v-if="pic_show && is_edit_add "
							style="display: flex;flex-direction: row; flex-wrap: wrap;">
							<view v-for="(item,index) in tupian_url" style="display: flex;">
								<view class="">
									<view @click="delpic1(index)"
										style="position: absolute;z-index: 99; display: flex;z-index: 99; width: 50rpx;height: 50rpx;border-radius: 50%;background-color: darkgray;color: white;justify-content: center;align-items: center;margin: 0 0 0 155rpx;">
										X
									</view>
									<image
										style="display: flex; width:200rpx;height: 200rpx;margin-right: 10rpx;margin-bottom: 10rpx; border-radius: 15rpx;"
										:src="item.fileID" mode="">
									</image>
								</view>
							</view>
						</view> 
						<view style="display: flex;justify-content: center;">
							<uni-file-picker v-if="pic_upload_show || !is_edit_add" limit="9" v-model="tupian_url"
								:del-icon="true" mode="grid" :imageStyles="imageStyles" file-mediatype="image"
								@select="select" @success="fanhuiurl" @delete="delpic"></uni-file-picker>
						</view>
					</view>
					<view style="display: flex;margin:30rpx 0 20rpx 0;align-items: center;">
						<view
							style="width:8rpx;height: 30rpx;background-color: blue;margin-right: 15rpx;border-radius: 15rpx;">
						</view>
						商品名称
					</view>
					<input style="padding: 15rpx 25rpx; border-radius: 9rpx;box-shadow: 1px 1px 5px #c2c2c2;"
						type="text" v-model="goods_name" focus placeholder="请输入商品的名称">
					<view style="display: flex;margin:30rpx 0 20rpx 0;align-items: center;">
						<view
							style="width:8rpx;height: 30rpx;background-color: blue;margin-right: 15rpx;border-radius: 15rpx;">
						</view>
						商品价格
					</view>
					<input style="padding: 15rpx 25rpx; border-radius: 9rpx;box-shadow: 1px 1px 5px #c2c2c2;"
						type="number" v-model="goods_price" focus placeholder="请输入商品的价格">
					<view style="display: flex;margin:30rpx 0 20rpx 0;align-items: center;">
						<view
							style="width:8rpx;height: 30rpx;background-color: blue;margin-right: 15rpx;border-radius: 15rpx;">
						</view>
						分类设置
					</view>
					<view style="display: flex;justify-content: space-between;margin-top: 25rpx;">
						<view>
							<view style="display: flex;justify-content: center;font-size:26rpx;margin-bottom: 10rpx;">
								所属分类一</view>
							<picker @change="fenleixuanze1" :range="goods_fenlei1">
								<u--input placeholder="请选择分类" :value="fenlei1" border="surround"></u--input>
							</picker>
						</view>
						<view class="">
							<view style="display: flex;justify-content: center;font-size:26rpx;margin-bottom: 10rpx;">
								所属分类二</view>
							<picker @change="fenleixuanze2" :range="goods_fenlei2">
								<u--input placeholder="请选择分类" :value="fenlei2" border="surround"></u--input>
							</picker>
						</view>
						<view class="">
							<view style="display: flex;justify-content: center;font-size:26rpx;margin-bottom: 10rpx;">
								所属分类三</view>
							<picker @change="fenleixuanze3" :range="goods_fenlei3">
								<u--input placeholder="请选择分类" :value="fenlei3" border="surround"></u--input>
							</picker>
						</view>
					</view>
					<view v-if="is_edit_add" style="display: flex;margin:30rpx 0 20rpx 0;align-items: center;">
						<view
							style="width:8rpx;height: 30rpx;background-color: blue;margin-right: 15rpx;border-radius: 15rpx;">
						</view>
						库存设置
					</view>
					<view v-for="(item,index) in kucunlist">
						<view
							style="display: flex;justify-content: space-between;align-items: center;margin-top: 23rpx;">
							<view class="">
								{{item.color}}--{{item.size}}
							</view>
							<input
								style="width:80rpx; padding: 5rpx 25rpx; border-radius: 9rpx;box-shadow: 1px 1px 5px #c2c2c2;"
								type="number" v-model.number="kucunlist[index].kucun" focus
								placeholder-style="font-size:20rpx" placeholder="库存数量">
						</view>
						<view style="width: 100%;height: 3rpx;background-color: #c2c2c2;margin-top: 10rpx;">

						</view>
					</view>
					<view @click="update_kucun" v-if="is_edit_add"
						style="display: flex;width: 170rpx;margin-top: 25rpx; height: 60rpx;font-size: 26rpx; background-color: blue;border-radius: 15rpx;justify-content: center;align-items: center;color: white;margin-left: auto;">
						库存更新
					</view>
					<view style="display: flex;margin:30rpx 0 20rpx 0;align-items: center;">
						<view
							style="width:8rpx;height: 30rpx;background-color: blue;margin-right: 15rpx;border-radius: 15rpx;">
						</view>
						商品详情
						<text style="font-size: 23rpx;color: darkgray;margin-left: 10rpx;">(建议专业网排好版，把代码复制进来)</text>
					</view>
					<u--textarea v-model="goods_detail" placeholder="请输入商品详情" maxlength="-1" height="80"></u--textarea>

					<view style="display: flex;flex-direction: row;margin-top: 80rpx;justify-content: center;">
						<view
							style="display: flex;width: 120rpx;border-radius: 15rpx;background-color: blue;color: white;justify-content: center;align-items: center;padding: 10rpx;"
							@click="tijiaoshangpin">
							{{is_edit_add?'修改':'提交'}}
						</view>
						<view
							style="display: flex;width: 120rpx;border-radius: 15rpx;background-color: blue;color: white;justify-content: center;align-items: center;margin-left: 60rpx;padding: 10rpx;"
							@click="goods_add_show = false">
							返回
						</view>
					</view>
					<view v-if="is_edit_add"
						style="display: flex;color: dodgerblue;margin-top: 50rpx;justify-content: center;"
						@click="shanchulunbotu(goods_id)">
						删除本商品
					</view>
				</view>
			</scroll-view>

		</model>
	</view>
</template>

<script>
	import getDateTime from '@/common/getdateTime.js';
	import model from '../../components/model.vue'
	export default {
		components: {
			model
		},
		data() {
			return {
				kucunlist: [],
				goods_kucun: [],
				goods_canshu: [],
				goods_canshu_list: [],
				phoneHeight: 0,
				goods_fenlei1: [],
				goods_fenlei2: [],
				goods_fenlei3: [],
				goods_fenlei1_id: [],
				goods_fenlei2_id: [],
				goods_fenlei3_id: [],
				fenlei1_id: '',
				fenlei2_id: '',
				fenlei3_id: '',
				fenlei1: '',
				fenlei2: '',
				fenlei3: '',
				isupload: 0,
				tuokeuserinfo: [],
				goods_detail: '',
				fenlei: '',
				goods_fenlei: [],
				imageStyles: {
					width: 100,
					height: 100,
					border: {
						radius: '20rpx'
					}
				},
				goods_list: [],
				goods_add_show: false, //添加商品时弹窗
				pic_show: true, //修改商品时，图片是否显示
				pic_upload_show: false, //修改商品时，图片上传窗口是否显示
				is_nogoods: 9, //是否有商品列表
				goods_name: '', //商品名称
				goods_price: '', //商品价格
				tupian_url: [], //商品图片的地址
				is_edit_add: '', //判断修改还是提交临时用
				goods_id: '', //商品的ID
				shu6: [],
			}
		},
		onLoad() {
			uni.getSystemInfo({
				success: (res) => {
					// 注意这里获得的高度宽度都是px，需要转换rpx
					// (res.screenHeight); // 屏幕高度，包含导航栏
					// (res.screenWidth); // 屏幕宽度
					// (res.windowHeight); // 可使用窗口高度，不包含导航栏
					// (res.windowWidth); // 可使用窗口宽度
					// 可使用窗口高度，将px转换rpx
					this.phoneHeight = (res.windowHeight * (750 / res.windowWidth))
				}
			})
			this.get_goods_fenlei()
			this.get_goods_fun()
			this.islogin()

		},
		methods: {
			del_kucun() {
				return uniCloud.callFunction({
					name: "fun1",
					data: {
						leixing: 11,
						tiaojian: {
							goods_id: this.goods_id,
						}
					}
				}).then(res => {})
			},
			async update_kucun() {
				try {
					// 等待删除操作完成
					await this.del_kucun();
					console.log("旧库存数据已清除");

					// 执行库存更新操作
					const res = await uniCloud.callFunction({
						name: "fun1",
						data: {
							leixing: 12,
							shuju: this.kucunlist
						}
					});
					console.log("更新成功:", res);
				} catch (e) {
					console.error("操作失败:", e);
					uni.showToast({
						title: "库存更新失败",
						icon: "none"
					});
				}
			},

			async suan_kucun_list() {
				await this.get_goods_canshu()
				await this.get_goods_kucun()
				// 将 goods_kucun 转换为 Map 提高查询效率
				const inventoryMap = new Map();
				this.goods_kucun.forEach(item => {
					const key = `${item.color}-${item.size}`; // 唯一标识符
					inventoryMap.set(key, item.kucun);
				});

				// 生成带有更新库存的新数组（保持原数组不变）
				const newKucunlist = await this.kucunlist.map(item => ({
					...item, // 保留原属性
					goods_id: this.goods_id,
					kucun: inventoryMap.get(`${item.color}-${item.size}`) || 0 // 匹配库存，无则默认为0
				}));

				// 使用新数组（根据场景选择是否替换原数组）
				this.kucunlist = newKucunlist;
			},
			
			// 获取商品参数（返回 Promise 链）
			get_goods_canshu() {
				return uniCloud.callFunction({ // 关键点：返回 Promise
					name: "fun1",
					data: {
						leixing: 8
					}
				}).then(res => {
					this.goods_canshu = res.result.data;
					this.kucunlist = [];
					// 生成库存初始结构
					this.goods_canshu[0].canshu.forEach(item1 => {
						this.goods_canshu[1].canshu.forEach(item2 => {
							this.kucunlist.push({
								color: item1,
								size: item2,
								kucun: 0
							});
						});
					});
				});
			},

			// 获取实际库存（返回 Promise）
			get_goods_kucun() {
				return uniCloud.callFunction({ // 关键点：返回 Promise
					name: "fun1",
					data: {
						leixing: 10,
						tiaojian: {
							goods_id: this.goods_id
						}
					}
				}).then(res => {
					this.goods_kucun = res.result.data;
				});
			},

			get_goods_fenlei() {
				uniCloud.callFunction({
					name: "fun1",
					data: {
						leixing: 1,
					}
				}).then(res => {
					res.result.data.map(item => {
						if (item.weizhi.includes("1")) {
							this.goods_fenlei1.push(item.name)
							this.goods_fenlei1_id.push(item._id)
						} else if (item.weizhi.includes("2")) {
							this.goods_fenlei2.push(item.name)
							this.goods_fenlei2_id.push(item._id)
						} else if (item.weizhi.includes("3")) {
							this.goods_fenlei3.push(item.name)
							this.goods_fenlei3_id.push(item._id)
						}
					})
				})
			},
			islogin() {
				let tuokeuserinfo = uni.getStorageSync('tuokeuserinfo')
				this.tuokeuserinfo = tuokeuserinfo
				if (!tuokeuserinfo) {
					uni.navigateTo({
						url: '/pages/denglu/denglu'
					});
				}

			},
			
			fenleixuanze1: function(e) {
				this.fenlei1 = this.goods_fenlei1[e.detail.value]
				this.fenlei1_id = this.goods_fenlei1_id[e.detail.value]
			},
			fenleixuanze2: function(e) {
				this.fenlei2 = this.goods_fenlei2[e.detail.value]
				this.fenlei2_id = this.goods_fenlei2_id[e.detail.value]
			},
			fenleixuanze3: function(e) {
				this.fenlei3 = this.goods_fenlei3[e.detail.value]
				this.fenlei3_id = this.goods_fenlei3_id[e.detail.value]
			},
			delpic1(n) {
				// 删除存储空间中的图片
				uniCloud.callFunction({
					name: "delpic",
					data: {
						leixing: 0,
						picurl:[this.tupian_url[0].url]
					}
				}).then(res => {})
				// 删除tupian_url中第n个元素
				if (this.tupian_url.length == 1) {
					this.tupian_url = []
					this.pic_show = false
					this.pic_upload_show = true
				} else {
					this.tupian_url.splice(n, 1)
				}
			},
			//删除图片
			delpic(e) {
				uniCloud.callFunction({
					name: "delpic",
					data: {
						leixing: 0,
						picurl: [e.tempFilePath]
					}
				}).then(res => {})
			},
			// 选择图片时，赋值0
			select() {
				this.isupload = 0
			},
			// 上传成功
			fanhuiurl(e) {
				this.isupload = 1
			},
			//获取商品
			get_goods_fun() {
				uniCloud.callFunction({
					name: "fun1",
					data: {
						leixing: 4, //获取商品
						tiaojian: {}
					}
				}).then(res => {
					if (res.result.data.length == 0) {
						this.is_nogoods = 0
					}
					this.goods_list = res.result.data
				})
			},
			//提交或修改商品
			tijiaoshangpin() {
				if (this.isupload == 0) {
					uni.showToast({
						title: '请上传完图片',
						icon: 'none',
						duration: 1000
					})
					return
				}
				if (this.is_edit_add) {
					if (!this.goods_name || !this.goods_price || !this.tupian_url.length || !this.goods_detail) {
						uni.showToast({
							title: '请填好各项，且上传图片再试',
							icon: 'none',
							duration: 1000
						})
						return
					}
				}
				if (!this.fenlei1 && !this.felei2 && this.fenlei3) {
					uni.showToast({
						title: '请至少选择一个分类',
						icon: 'none',
						duration: 1000
					})
					return
				}
				this.goods_add_show = false
				const shuju = {
					tupian_url: this.tupian_url,
					goods_name: this.goods_name,
					goods_price: this.goods_price,
					fenlei1: this.fenlei1,
					fenlei1_id: this.fenlei1_id,
					fenlei2: this.fenlei2,
					fenlei2_id: this.fenlei2_id,
					fenlei3: this.fenlei3,
					fenlei3_id: this.fenlei3_id,
					goods_detail: this.goods_detail,
					update_time: getDateTime.dateTimeStr('y-m-d h:i:s')
				}
				if (this.is_edit_add) {
					uniCloud.callFunction({
						name: "fun1",
						data: {
							leixing: 2, //修改商品
							id: this.goods_id,
							shuju: shuju
						}
					}).then(res => {
						this.get_goods_fun()
						this.goods_name = this.goods_price = this.is_edit_add = this.goods_id =
							this.goods_detail = ''
						this.tupian_url = []
					})
				} else {
					uniCloud.callFunction({
						name: "fun1",
						data: {
							leixing: 3, //修改商品
							shuju: shuju
						}
					}).then(res => {
						this.get_goods_fun()
						this.goods_name = this.goods_price = this.is_edit_add = this.goods_id =
							this.goods_detail = ''
						this.tupian_url = []
					})
				}
				this.pic_show = true
				this.pic_upload_show = false
			},
			//点击进入商品修改页面
			to_goods(e) {
				if (e) { //下面是修改原有的商品
					this.isupload = 1
					this.goods_add_show = true
					this.goods_name = this.goods_price = this.is_edit_add = this.goods_id = this
						.fenlei1 = this.goods_detail = this.fenlei2 = this.fenlei3 = ''
					this.fenlei1_id = this.fenlei2_id = this.fenlei3_id = ''
					this.tupian_url = []
					this.is_edit_add = "1"
					this.tupian_url = e.tupian_url
					this.goods_name = e.goods_name
					this.goods_price = e.goods_price
					this.fenlei1 = e.fenlei1
					this.fenlei1_id = e.fenlei1_id
					this.fenlei2 = e.fenlei2
					this.fenlei2_id = e.fenlei2_id
					this.fenlei3 = e.fenlei3
					this.fenlei3_id = e.fenlei3_id
					this.goods_detail = e.goods_detail
					this.goods_id = e._id
					this.suan_kucun_list()
					if (this.tupian_url.length == 0) {
						this.pic_show = false
						this.pic_upload_show = true
					}
				} else { //下面是添加新商品
					// this.get_goods_canshu()
					this.goods_add_show = true
					this.goods_name = this.goods_price = this.is_edit_add = this.goods_id = this
						.fenlei1 = this.goods_detail = this.fenlei2 = this.fenlei3 = ''
					this.fenlei1_id = this.fenlei2_id = this.fenlei3_id = ''
					this.tupian_url = []
					this.is_edit_add = ""
				}

			},
			//删除本张商品
			shanchulunbotu() {
				this.goods_add_show = false
				//删除图片文件 
				uniCloud.callFunction({
					name: "delpic",
					data: {
						picurl: this.tupian_url.map(item => item.url) ,
						leixing: 0, //删除头像
					}
				}).then(res => {})
				this.del_kucun()
				//删除本条记录
				uniCloud.callFunction({
					name: "fun1",
					data: {
						id: this.goods_id,
						leixing: 13, //删除本条记录
					}
				}).then(res => {
					this.get_goods_fun()
				})
				
			},
		}
	}
</script>

<style>

</style>